package com.novel.controller.system;

import com.novel.common.enums.UserIdentifyEnum;
import com.novel.controller.other.BaseController;
import com.novel.common.exception.CustomerException;
import com.novel.pojo.system.User;
import com.novel.service.NovelShelfService;
import com.novel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;


/**
 * 用户相关的控制器方法
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    @Autowired
    private UserService service;

    @Autowired
    private NovelShelfService shelfService;


    /**
     * 实时用户用户账户余额信息
     */
    @PostMapping("amount")
    public String getUserAmount() {

        User user = getUserInformation();
        if (Objects.isNull(user)) {
            throw new CustomerException("用户未登录!");
        }

        User nowUser = service.getUserInfo(user.getUserId());

        return "账户余额：" + nowUser.getAmount();
    }


    /**
     * 用户登录
     * 判断用户是否登录成功
     * 如果用户登录成功，则把用户信息保存到会话域中
     *
     * @param email    邮箱
     * @param password 密码
     */
    @PostMapping("login")
    public ResponseEntity<Boolean> UserLogin(String email, String password) {
        //判断是否登录成功
        User user = service.Login(email, password);
        if (checkUserPermission(UserIdentifyEnum.READER, user.getIdentify())) {
            //把用户信息保存到会话域中
            setUserInformation(user);
            return ResponseEntity.ok(true);
        }
        throw new CustomerException("您没有登录登录");
    }

    /**
     * 邮箱验证登录
     *
     * @param email 邮箱
     * @param code  验证码
     */
    @PostMapping("/email/login")
    public ResponseEntity<Boolean> EmailLogin(String email, String code) {
        //验证码是否正确输入
        if (compareVerCode(code)) {
            User user = service.LoginByEmail(email);
            setUserInformation(user);
            //全部验证通过，删除验证码
            session.removeAttribute("time");
            return ResponseEntity.ok(true);
        }
        throw new CustomerException("验证码输入错误");
    }

    /**
     * 用户注册功能
     *
     * @param user      封装好的用户信息
     * @param emailCode 邮箱验证码
     */
    @PostMapping("/register")
    @ResponseBody
    public ResponseEntity<Boolean> UserRegister(@Valid User user, BindingResult result, String emailCode) {
        //获得信息封装异常
        List<FieldError> errorList = result.getFieldErrors();
        if (errorList.size() == 0) {
            //其中没有异常，可以直接使用
            //判断是否验证通过
            if (compareVerCode(emailCode)) {
                //注册用户到数据库中
                boolean get = service.Register(user);
                if (get) {
                    //全部验证通过，删除验证码
                    session.removeAttribute("time");
                }
                return ResponseEntity.ok(get);
            }
            throw new CustomerException("验证码输入错误");
        }
        throw new CustomerException(errorList.get(0).getDefaultMessage());
    }

    /**
     * 修改密码，用于登录之后想要修改自己的密码
     *
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     */
    @PostMapping("/change-online")
    public boolean ChangePasswordOnline(String oldPassword, String newPassword) {
        //获取当前登录人的信息
        User user = getUserInformation();
        //比较输入的旧密码是否相同
        if (user.getPassword().equals(oldPassword)) {
            //把旧密码替换掉
            user.setPassword(newPassword);
            //尝试修改密码
            boolean result = service.ChangePassword(user);
            //判断是否修改成功
            if (result) {
                //覆盖session中的信息
                setUserInformation(user);
            }
            return result;
        }
        return false;
    }

    /**
     * 修改密码，用于忘记密码申请修改的时候
     *
     * @param email       邮箱
     * @param newPassword 新的密码
     * @return
     */
    @PostMapping("/change-mail")
    public boolean ChangePasswordEmail(String email, String newPassword, String code) {
        //对比邮件验证码
        if (compareVerCode(code)) {
            //创建用户对象封装数据
            User user = new User();
            user.setUserEmail(email);
            user.setPassword(newPassword);
            //修改密码
            return service.ChangePasswordByEmail(user);
        }
        throw new CustomerException("验证码错误");
    }

    /**
     * 用户个人信息修改
     */
    @PostMapping("/change/personal")
    public boolean ChangePersonal(User user) {
        //获取对应的信息，封装到user中
        User old = getUserInformation();
        if (old == null) {
            //用户未登录，异常返回给页面
            throw new CustomerException("请登录");
        }
        //封装用户的其他信息到user中
        user.setUserId(old.getUserId());
        user.setUserEmail(old.getUserEmail());
        return service.ChangePersonal(user);
    }

    /**
     * 用户注销
     * 需要删除本次会话用户的登录信息
     */
    @GetMapping("/cancel")
    public ModelAndView UserCancel(ModelAndView mv) {
        //清空会话域中的用户信息
        clearUserInformation();
        //设置对用的页面
        mv.setViewName("redirect:/index");
        //返回数据给页面，让页面进行跳转
        return mv;
    }

}
